package com.shishi.fast.generator.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shishi.fast.common.exception.ApiException;
import com.shishi.fast.common.util.DateTimeUtils;
import com.shishi.fast.common.vo.ResultCode;
import com.shishi.fast.generator.domain.CheckRecordDO;
import com.shishi.fast.generator.domain.DeviceDO;
import com.shishi.fast.generator.domain.DeviceTemplateDO;
import com.shishi.fast.generator.excel.CheckRecordImportExcel;
import com.shishi.fast.generator.mapper.CheckRecordMapper;
import com.shishi.fast.generator.mapper.DeviceMapper;
import com.shishi.fast.generator.mapper.DeviceTemplateMapper;
import com.shishi.fast.generator.service.CheckRecordService;
import com.shishi.fast.generator.vo.CheckRecordRequest;
import com.shishi.fast.generator.vo.TemplateResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class CheckRecordServiceImpl extends ServiceImpl<CheckRecordMapper, CheckRecordDO> implements CheckRecordService {

    @Autowired
    private CheckRecordMapper checkRecordMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceTemplateMapper deviceTemplateMapper;

    @Override
    public void generateData(CheckRecordRequest.GenerateDataParam param) {
        List<DeviceDO> deviceDOList = deviceMapper.selectList(Wrappers.<DeviceDO>lambdaQuery()
                .eq(DeviceDO::getCompanyId, param.getCompanyId())
                .eq(DeviceDO::getDeleted, 0)
        );

        for (DeviceDO deviceDO : deviceDOList) {
            List<CheckRecordDO> list = generateInspectionData(param.getStartDate(), param.getEndDate(), deviceDO);
            this.saveBatch(list);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importExcel(MultipartFile file, String companyId) {
        ImportParams params = new ImportParams();

        List<CheckRecordImportExcel> importExcelList = new ArrayList<>();
        try {
            importExcelList = ExcelImportUtil.importExcel(file.getInputStream(), CheckRecordImportExcel.class, params);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (ObjectUtils.isEmpty(importExcelList)) {
            throw new ApiException(ResultCode.FAILED);
        }

        for (CheckRecordImportExcel checkRecordImportExcel : importExcelList) {
            DeviceDO deviceDO = deviceMapper.selectOne(Wrappers.<DeviceDO>lambdaQuery()
                    .eq(DeviceDO::getCompanyId, companyId)
                    .eq(DeviceDO::getDeviceNo, checkRecordImportExcel.getDeviceNo())
            );
            if (ObjectUtils.isEmpty(deviceDO)) {
                throw new ApiException(ResultCode.FAILED);
            }

            CheckRecordDO checkRecordDO = new CheckRecordDO();
            BeanUtils.copyProperties(checkRecordImportExcel, checkRecordDO);

            //固定参数
            checkRecordDO.setCompanyId(companyId);
            checkRecordDO.setDeviceId(deviceDO.getId());

            //加工点检内容
            List<Map<String, Object>> mapList = new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("title", "日常点检");
            map1.put("checked", "true");
            mapList.add(map1);

//            Map<String, Object> map2 = new HashMap<>();
//            map2.put("title", "各高低接头处是否有渗漏");
//            map2.put("checked", "true");
//            mapList.add(map2);
//
//            Map<String, Object> map3 = new HashMap<>();
//            map3.put("title", "设备各润滑点状况是否正常");
//            map3.put("checked", "true");
//            mapList.add(map3);
//
//            Map<String, Object> map4 = new HashMap<>();
//            map4.put("title", "检查各挡位、开关、旋钮在原位或设定的位置");
//            map4.put("checked", "true");
//            mapList.add(map4);
//
//            Map<String, Object> map5 = new HashMap<>();
//            map5.put("title", "检查各罐装头是否有滴漏、堵塞");
//            map5.put("checked", "true");
//            mapList.add(map5);

            checkRecordDO.setCheckContent(JSONObject.toJSONString(mapList));
            checkRecordDO.setUpdateTime(checkRecordImportExcel.getCreateTime());

            checkRecordMapper.insert(checkRecordDO);
        }
    }

    public List<CheckRecordDO> generateInspectionData(String startDateStr, String endDateStr, DeviceDO deviceDO) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        Date startDate = null;
        Date endDate = null;
        try {
            startDate = dateFormat.parse(startDateStr + " 07:00");
            endDate = dateFormat.parse(endDateStr + " 18:00");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        //查询模版，如果模版为空则报错
        DeviceTemplateDO deviceTemplateDO = deviceTemplateMapper.selectById(deviceDO.getCheckTemplateId());
        if (org.apache.commons.lang3.ObjectUtils.isEmpty(deviceTemplateDO)) {
            throw new ApiException(ResultCode.FAILED, "未查询到设备绑定的维修模版");
        }

        List<CheckRecordDO> checkRecordDOList = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);

        while (cal.getTime().before(endDate)) {
            CheckRecordDO checkRecordDO = new CheckRecordDO();

            checkRecordDO.setCompanyId(deviceDO.getCompanyId());
            checkRecordDO.setDeviceId(deviceDO.getId());

            //获取模版内容
            List<TemplateResponse.TemplateContent> templateContentList = JSONArray.parseArray(deviceTemplateDO.getTemplateContent(), TemplateResponse.TemplateContent.class);
            //存入结果
            List<TemplateResponse.TemplateResult> templateResultList = new ArrayList<>();
            for (TemplateResponse.TemplateContent templateContent : templateContentList) {
                TemplateResponse.TemplateResult templateResult = new TemplateResponse.TemplateResult();
                BeanUtils.copyProperties(templateContent, templateResult);
                templateResult.setChecked("true");
                templateResultList.add(templateResult);
            }
            //转换字符串存入对象
            checkRecordDO.setCheckContent(JSONObject.toJSONString(templateResultList));


            Date inspectionStartTime = DateTimeUtils.getRandomTime(cal.getTime(), 7, 8);
            Date inspectionEndTime = DateTimeUtils.getRandomEndTime(inspectionStartTime, 0.17, 0.33);

            int randomNumber = new Random().nextInt(5) + 1;

            checkRecordDO.setCreateBy("管理员" + randomNumber);
            checkRecordDO.setCreateTime(inspectionStartTime);
            checkRecordDO.setUpdateTime(inspectionEndTime);

            checkRecordDOList.add(checkRecordDO);

            cal.add(Calendar.DATE, 1); // 每天生成一条
        }
        return checkRecordDOList;
    }

}




